/**
 * 
 */
package com.ctrip.cap.internal.appium.suite.ios;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.ISuite;

import com.ctrip.cap.common.exception.CapException;
import com.ctrip.cap.device.exceptions.IOSDeviceException;
import com.ctrip.cap.device.ios.IOSDevice;
import com.ctrip.cap.device.ios.impl.IPhoneDeviceStore;
import com.ctrip.cap.internal.suite.SuiteManListener;
import com.ctrip.cap.internal.util.HttpUtils;
import com.ctrip.cap.lanucher.AppiumConfig;
import com.ctrip.cap.lanucher.Environment;
import com.ctrip.cap.monitor.common.DeviceManager;

/**
 * @author zwxu
 *
 */
public class IOSStartupListener {

	Logger logger = LoggerFactory.getLogger(IOSStartupListener.class);

	public void onExecutionStart(ISuite suite) {
		logger.info("[[runMode={}]]onExecutionStart", Environment.isLabName());

		AppiumConfig config = (AppiumConfig) suite
				.getAttribute(SuiteManListener.CAP_CONFIG);

		for (IOSDevice device : IPhoneDeviceStore.getInstance().getDevices()) {
			config.setDeviceName(device.getSerialNumber());
			config.setPlatformVersion(device.getPlatformVersion());
		}

		// IOS Pre-process
		preparePackage(config);

		// Monitor start
		// if (Environment.isLab()) {
		// DeviceManager.start();
		// }

	}

	public void onExecutionFinish() {
		try {
			if (Environment.isLab()) {
				DeviceManager.stop();
			}
			// shutdown server
			IPhoneDeviceStore.getInstance().shutdownForcely();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}

	}

	private void preparePackage(AppiumConfig appiumConfig) {

		if (appiumConfig.getDriverType().isH5()) {
			return;
		}

		if (Environment.isLab()) {
			String app = Environment.getAppPath();
			if (StringUtils.isNotBlank(app)) {
				appiumConfig.setApp(app);
			}
		}

		String app = appiumConfig.getApp();
		String finalAppPath = null;
		String fileName = "ctrip.ipa";
		for (IOSDevice device : IPhoneDeviceStore.getInstance().getDevices()) {
			if (StringUtils.isBlank(app)) {
				appiumConfig.setApp("com.ctrip.inner.wireless");
			} else if (app.toLowerCase().endsWith(".ipa")) {

				if (app.toLowerCase().startsWith("http")) {
					app = HttpUtils.downloadApp(app);
				}

				// it will failed to install once the package name contains
				// Chinese char
				finalAppPath = FilenameUtils.getFullPath(app) + fileName;

				try {
					FileUtils.deleteQuietly(new File(finalAppPath));
					FileUtils.moveFile(new File(app), new File(finalAppPath));
				} catch (IOException e) {
					throw new CapException("file rename", e);
				}

				appiumConfig.setApp(finalAppPath);
				appiumConfig.setAppFileName(fileName);

				installApp(device, appiumConfig);
			}

			// Now app is bundleID, verify it exists on devices.
			if (!device.isInstalled(appiumConfig.getApp())) {
				throw new IOSDeviceException("Conldn't find app: " + app
						+ " on Device : " + device.getSerialNumber());
			}
		}
	}

	private void installApp(IOSDevice device, AppiumConfig config) {
		// auto get buildID later, hard code for now,
		if (device.isInstalled("com.ctrip.inner.wireless")) {
			device.uninstall("com.ctrip.inner.wireless");
		}
		device.install(config.getApp());

		config.setApp("com.ctrip.inner.wireless");
	}
}
